180. Consecutive Numbers


Posted by ikl258794613 on 2024-02-26

Table: Logs

Column Name Type
id int
num varchar

In SQL, id is the primary key for this table.
id is an autoincrement column.

Find all numbers that appear at least three times consecutively.

Return the result table in any order.

The result format is in the following example.

Example 1:

Input:
Logs table:

id num
1 1
2 1
3 1
4 2
5 1
6 2
7 2

Output:

ConsecutiveNums
1

Explanation: 1 is the only number that appears consecutively for at least three times.


SELECT l1.num AS ConsecutiveNums
FROM Logs l1
LEFT JOIN Logs l2
ON (L1.id+1) = l2.id
LEFT JOIN Logs l3
ON (L1.id+2) = l3.id
WHERE l1.num = l2.num AND l2.num = l3.num
GROUP BY l1.num

解題思路:
先把自己join起來,在把l1.num = l2.num AND l2.num = l3.num取出來


SELECT *
FROM Logs l1
LEFT JOIN Logs l2
ON (L1.id+1) = l2.id
LEFT JOIN Logs l3
ON (L1.id+2) = l3.id
id num id num id num
1 1 2 1 3 1
2 1 3 1 4 2
3 1 4 2 5 1
4 2 5 1 6 2
5 1 6 2 7 2
6 2 7 2 null null
7 2 null null null null

#SQL







Related Posts

給 TensorFlow 初學者或害怕複雜 API 的人的學習建議

給 TensorFlow 初學者或害怕複雜 API 的人的學習建議

C# String相關應用

C# String相關應用

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段二:專題研討+協作練習專案)

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段二:專題研討+協作練習專案)


Comments